package com.sundae.smarthomedemo.Activitys;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;
import com.sundae.smarthomedemo.MyAppConfig;
import com.sundae.smarthomedemo.R;
import com.sundae.smarthomedemo.Utils.MyAppUtils;
import com.sundae.smarthomedemo.Utils.ToastUtils;
import com.sundae.smarthomedemo.Utils.WifiAdmin;
import com.sundae.smarthomedemo.Widget.DeviceDialog;
import com.yanzhenjie.permission.AndPermission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import immortalz.me.library.TransitionsHeleper;
import immortalz.me.library.bean.InfoBean;
import immortalz.me.library.method.ColorShowMethod;

public class SelectWiFiActivity extends BaseActivity {

    private ImageView look_image;
    private EditText wifipwd_et;
    private TextView wifiName_tv;
    private Button scan_btn;
    private List<ScanResult> scanResults;
    private WifiAdmin wifiAdmin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_wi_fi);

        if(MyAppConfig.user_name.equals("")){
            ToastUtils.showLongToast(getApplicationContext(), "请先登陆");
            startActivity(new Intent(SelectWiFiActivity.this , LoginActivity.class));
            finish();
        }

        TransitionsHeleper.getInstance()
                .setShowMethod(new ColorShowMethod(R.color.grayColor,R.color.styleColor) {
                    @Override
                    public void loadCopyView(InfoBean bean, ImageView copyView) {
                        AnimatorSet set = new AnimatorSet();
                        set.playTogether(
                                ObjectAnimator.ofFloat(copyView,"rotation",0,180),
                                ObjectAnimator.ofFloat(copyView, "scaleX", 1, 0),
                                ObjectAnimator.ofFloat(copyView, "scaleY", 1, 0)
                        );
                        set.setInterpolator(new AccelerateInterpolator());
                        set.setDuration(duration / 4 * 5).start();
                    }

                    @Override
                    public void loadTargetView(InfoBean bean, ImageView targetView) {
                    }
                })
                .show(this,null);


        StatusBarUtil.setColor(this , getResources().getColor(R.color.styleColor) , 0);

        AndPermission.with(this)
                .permission(Manifest.permission.ACCESS_FINE_LOCATION ,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.INTERNET
                )
                .start();

        initView();

    }

    @Override
    protected void onStart() {
        super.onStart();

        if (!MyAppUtils.isGPSOpen(getApplicationContext())) {
            ToastUtils.showLongToast(getApplicationContext() , "请打开定位");
            MyAppUtils.openGPS(getApplicationContext());
        }

        scan_btn.setEnabled(true);
    }

    private void initView()
    {
        look_image = (ImageView) findViewById(R.id.look_image);
        wifipwd_et = (EditText) findViewById(R.id.wifi_pwd_editText);
        wifiName_tv = (TextView) findViewById(R.id.wifi_name_text);
        scan_btn = (Button) findViewById(R.id.select_wifi_scan_button);

        wifiName_tv.setText("当前Wi-Fi：" + MyAppUtils.getWifiName(getApplicationContext()));

        look_image.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN)
                {
                    wifipwd_et.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    look_image.setBackground(ContextCompat.getDrawable(getApplicationContext() , R.drawable.look_down));
                    wifipwd_et.setSelection(wifipwd_et.getText().length());
                    return true;
                }else if(event.getAction() == MotionEvent.ACTION_UP)
                {
                    wifipwd_et.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    look_image.setBackground(ContextCompat.getDrawable(getApplicationContext() , R.drawable.look));
                    wifipwd_et.setSelection(wifipwd_et.getText().length());
                    return true;
                }
                return false;
            }
        });


        findViewById(R.id.select_backButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelectWiFiActivity.this.finish();
            }
        });

        findViewById(R.id.wifi_name_text).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN)
                {
                    v.setBackground(ContextCompat.getDrawable(getApplicationContext() , R.drawable.wifi_name_pressed));
                }else if(event.getAction() == MotionEvent.ACTION_UP)
                {
                    v.setBackground(ContextCompat.getDrawable(getApplicationContext() , R.drawable.wifi_name_normal));
                    initWiFi();
                }
                return false;
            }
        });

        scan_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scan_btn.setEnabled(false);
                ToastUtils.showLongToast(SelectWiFiActivity.this , "现在我们假设连接上了WIFI");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent();
                        intent.setClass(SelectWiFiActivity.this , DeviceSelectActivity.class);
                        TransitionsHeleper.startActivity(SelectWiFiActivity.this , intent , scan_btn);
                    }
                } , 1300);
            }
        });

    }

    private ArrayList<HashMap<String , String>> deviceList = new ArrayList<>();
    private HashMap<String , String> map;
    private DeviceDialog deviceDialog;
    private void initWiFi()
    {
        deviceList.clear();
        wifiAdmin = new WifiAdmin(getApplicationContext());
        wifiAdmin.startScan();
        scanResults = wifiAdmin.getWifiList();
        for(ScanResult scanResult : scanResults)
        {
            map = new HashMap<>();
            map.put("ssid" , scanResult.SSID);
            map.put("haspwd" , scanResult.capabilities.trim().equals("[ESS]") ? "无加密" : "有加密");
            deviceList.add(map);
        }
        deviceDialog = new DeviceDialog(SelectWiFiActivity.this , R.style.NobackDialog , deviceList);
        deviceDialog.setCallBack(new DeviceDialog.CallBack() {
            @Override
            public void onDeviceSelected(String ssid, boolean hasPwd) {
                wifiName_tv.setText("当前Wi-Fi：" + ssid);
                if(hasPwd)
                {
                    wifipwd_et.setEnabled(true);
                    wifipwd_et.setHint("Wi-Fi密码：");
                    wifipwd_et.setBackground(ContextCompat.getDrawable(getApplicationContext() ,R.drawable.wifi_pwd_text_style));
                }
                else {
                    wifipwd_et.setEnabled(false);
                    wifipwd_et.setHint("无需密码");
                    wifipwd_et.setBackground(ContextCompat.getDrawable(getApplicationContext() ,R.drawable.wifi_name_normal));
                }
                deviceDialog.dismiss();
            }
        });
        deviceDialog.show();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.down_in, R.anim.down_out);
    }
}
